from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from libs.common_jwt import JwtToken
from user.models import User
from django.core.cache import cache
import jwt


class UserAuthenticate(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if not token:
            raise AuthenticationFailed("登录信息缺失")
        try:
            valid_token = JwtToken.get_payload(token=token)
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed("Token已过期")
        except jwt.DecodeError:
            raise AuthenticationFailed("Token无效")
        user_id = valid_token['id']
        old_token = cache.get(f'token_{user_id}')
        if old_token != token:
            raise AuthenticationFailed('当前token已失效，请重新登录')
        user = User.objects.get(pk=user_id)
        return user, token
